<template>
  <div class="approval-page">
    <!-- 顶部操作卡片：返回 + 刷新 -->
    <el-card shadow="hover" class="top-action-card">
      <div class="top-actions">
        <BackButton text="返回首页" back-type="route" route-path="/index" :loading="loading" />
        <el-button type="info" :icon="Refresh" @click="refreshData" :loading="loading">
          刷新数据
        </el-button>
      </div>
    </el-card>

    <!-- 刷新遮罩层 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-content">
        <el-icon class="loading-icon">
          <Loading />
        </el-icon>
        <span class="loading-text">正在刷新数据...</span>
      </div>
    </div>

    <!-- JSON 展示 -->
    <div class="json-container">
      <el-card shadow="hover" class="json-card-with-button">
        <template #header>
          <div class="header-content">
            <el-icon class="header-icon">
              <Document />
            </el-icon>
            <span>{{ title || '申请信息' }}</span>
          </div>
        </template>

        <!-- 通用数据展示区域 -->
        <div class="json-display-content">
          <GenericDataDisplay :data="jsonData" />
        </div>

      </el-card>
    </div>

    <!-- 审批流程展示 -->
    <div class="table-container">
      <ApprovalFlowDisplay :business-type="businessType" :business-id="businessId" title="审批流程" :auto-load="true"
        :show-collapse="true" />
    </div>

    <!-- 审批弹窗 Dialog -->
    <el-dialog :title="approvalForm.statusLabel" v-model="dialogVisible" destroy-on-close :modal-append-to-body="true"
      top="15vh" width="520px" class="approval-dialog">
      <div class="approval-dialog-content">
        <el-form :model="approvalForm" label-width="100px" label-position="left">
          <el-form-item label="审核意见" class="approval-form-item">
            <el-input type="textarea" v-model="approvalForm.comment" placeholder="请输入审核意见（选填）" :rows="5" maxlength="500"
              show-word-limit resize="vertical" />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button size="large" @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" size="large" @click="submitApproval">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 悬浮审批按钮 -->
    <div class="floating-approval-buttons" v-if="flag === 0">
      <el-tooltip content="审核通过" placement="top">
        <el-button type="success" class="floating-button approve-button" @click="openApproval('同意')">
          审核通过
        </el-button>
      </el-tooltip>
      <el-tooltip content="审核不过" placement="top">
        <el-button type="danger" class="floating-button reject-button" @click="openApproval('拒绝')">
          审核不过
        </el-button>
      </el-tooltip>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { Document, Refresh, Loading, Check, Close } from '@element-plus/icons-vue'
import { ApprovalAuditBo } from '@/api/other/approval/types';
import { audit, getApprovalInstance, queryJsonData } from '@/api/other/approval'
import { useRoute, useRouter } from 'vue-router';
import BackButton from '@/views/project/components/PageHeader/BackButton.vue';
import ApprovalFlowDisplay from '@/components/ApprovalFlowDisplay/index.vue';
import GenericDataDisplay from '@/components/GenericDataDisplay/index.vue';


const route = useRoute();
const router = useRouter();
// 顶层声明，可全局使用
const id = ref<number | undefined>(undefined)
const flag = ref<number | undefined>(undefined)
const instanceId = ref<number | undefined>(undefined)
const businessId = ref<number | undefined>(undefined)
const businessType = ref<string | undefined>(undefined)
const title = ref<string>('申请信息')
const loading = ref(false)
const dialogVisible = ref(false)
const approvalForm = reactive({ status: undefined, comment: '', statusLabel: '' })
const jsonData = reactive<Record<string, any>>({})
const statusMap: Record<string, number> = { 同意: 1, 拒绝: 2, 退回: 3 }

// 初始化示例数据
onMounted(async () => {
  const routeState = history.state
  id.value = routeState?.id
  flag.value = routeState?.flag
  title.value = routeState?.title || '申请信息'
  if (id.value && flag.value !== undefined) {
    await getApprovalInstanceData()  // 等待数据返回
    console.log('获取审批详情：', instanceId.value, businessType.value)

    if (instanceId.value && businessType.value) {
      getJsonData()
    }
  }
})


// 点击审批按钮
function openApproval(status: string) {
  approvalForm.status = statusMap[status]
  approvalForm.statusLabel = status
  approvalForm.comment = ''
  dialogVisible.value = true
}

const submitApproval = async () => {
  const auditData: ApprovalAuditBo = {
    businessId: businessId.value,
    businessType: businessType.value,
    status: approvalForm.status,
    idea: approvalForm.comment,
  }

  try {
    await audit(auditData)
    ElMessage.success('审核成功')
    dialogVisible.value = false
    flag.value = 1
    router.back()
  } catch (error) {
    console.error('审核失败:', error)
    ElMessage.error('审核失败，请稍后再试')
  }
}



// 获取审批实例数据
const getApprovalInstanceData = async () => {
  try {
    console.log('获取审批记录：', id, flag)
    const response = await getApprovalInstance(id.value, flag.value) // AxiosResponse
    const instance = response  // 取 data
    console.log('instance:', instance)
    instanceId.value = Number(instance.id)
    businessId.value = Number(instance.businessId)
    businessType.value = instance.businessType
  } catch (err) {
    console.error('获取审批记录失败:', err)
  }
}

// 获取json数据
const getJsonData = async () => {
  try {
    console.log('获取审批记录：', instanceId)
    const response = await queryJsonData(businessType.value, businessId.value)
    const details = response as any // 临时类型转换
    console.log('原始响应数据:', details)
    
    // 清空之前的数据
    Object.keys(jsonData).forEach(key => {
      delete jsonData[key]
    })
    
    // 直接将响应数据赋值给jsonData，让通用组件自动处理
    Object.keys(details).forEach(key => {
      const value = details[key]
      if (value !== null && value !== undefined) {
        jsonData[key] = value
      }
    })
    
    console.log('处理后的jsonData:', jsonData)
  } catch (err) {
    console.error('获取审批详情失败:', err)
  }
}


// 映射审批结果数字到文字
const mapApprovalResult = (val: string) => {
  switch (val) {
    case '0':
      return '待审批'
    case '1':
      return '同意'
    case '2':
      return '驳回'
    default:
      return '未知'
  }
}



// 判断是否为包含type属性的对象
function isObjectWithType(val: any): boolean {
  return val && typeof val === 'object' && !Array.isArray(val) && 'value' in val && 'type' in val
}

// 获取显示值
function getDisplayValue(val: any): string {
  if (isObjectWithType(val)) {
    // 如果是Dict类型且有映射信息，使用映射后的值
    if (val.type === 'Dict' && val.mapping && val.value) {
      return val.mapping[val.value] || val.value
    }
    return val.value || ''
  }
  return val || ''
}

// 获取字段类型
function getFieldType(val: any): string {
  if (isObjectWithType(val)) {
    return val.type || 'String'
  }
  return 'String'
}

// 根据类型获取标签颜色
function getTypeTagType(type: string): string {
  const typeMap: Record<string, string> = {
    'String': 'info',
    'Text': 'info',
    'Number': 'warning',
    'BigDecimal': 'warning',
    'Date': 'success',
    'Boolean': 'primary',
    'Dict': 'danger',
    'Long': 'warning'
  }
  return typeMap[type] || 'info'
}

// 根据类型获取值样式类
function getValueClass(type: string): string {
  const classMap: Record<string, string> = {
    'String': 'value-string',
    'Text': 'value-text',
    'Number': 'value-number',
    'BigDecimal': 'value-number',
    'Date': 'value-date',
    'Boolean': 'value-boolean',
    'Dict': 'value-dict',
    'Long': 'value-number'
  }
  return classMap[type] || 'value-string'
}

// 保留必要的工具函数，供其他部分使用
// 判断是否为长内容
function isLongContent(value: any): boolean {
  const displayValue = getDisplayValue(value)
  return displayValue && displayValue.length > 50
}

// 根据值获取样式类（通用方法）
function getValueStyleClass(value: any): string {
  if (isObjectWithType(value)) {
    const type = getFieldType(value)
    return getValueClass(type)
  }
  return 'value-string'
}

// 刷新数据
async function refreshData() {
  loading.value = true
  try {
    if (instanceId.value && businessType.value) {
      await getJsonData()
    }
  } catch (error) {
    console.error('刷新数据失败:', error)
    ElMessage.error('刷新数据失败')
  } finally {
    loading.value = false
  }
}

</script>

<style scoped>
.approval-page {
  background-color: #f5f5f5;
  padding-top: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 24px;
  min-height: 100vh;
}

/* 顶部操作卡片 */
.top-action-card {
  width: 90%;
  max-width: 1200px;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.top-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/* 刷新遮罩层 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  background: #ffffff;
  padding: 32px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
}

.loading-icon {
  font-size: 32px;
  color: #409eff;
  animation: spin 1s linear infinite;
}

.loading-text {
  font-size: 16px;
  color: #606266;
  font-weight: 500;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

.json-container,
.table-container {
  width: 90%;
  max-width: 1200px;
}

.json-card-with-button {
  position: relative;
  padding-bottom: 60px;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

/* 标题样式 */
.header-content {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.header-icon {
  font-size: 20px;
  color: #409eff;
}

.json-display-content {
  padding: 20px 0;
}

.json-display-content .data-section:not(:last-child) {
  margin-bottom: 24px;
}

/* 数据区域样式 */
.data-section {
  margin-bottom: 24px;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border-left: 4px solid #409eff;
}

.section-title {
  margin: 0 0 20px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebeef5;
}

.section-title i {
  color: #409eff;
  font-size: 18px;
}

/* 数据列表样式 */
.data-list {
  display: flex;
  flex-direction: column;
  gap: 0;
}

.data-row {
  display: flex;
  align-items: flex-start;
  padding: 16px 0;
  border-bottom: 1px solid #f0f2f5;
  transition: background-color 0.2s ease;
}

.data-row:last-child {
  border-bottom: none;
}

.data-row:hover {
  background-color: #fafbfc;
  border-radius: 6px;
  margin: 0 -8px;
  padding: 16px 8px;
}

.data-row.long-content {
  flex-direction: column;
  align-items: flex-start;
}

.data-label {
  min-width: 140px;
  max-width: 200px;
  font-weight: 600;
  color: #2c3e50;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  padding: 8px 12px;
  border-radius: 6px;
  margin-right: 16px;
  flex-shrink: 0;
  font-size: 14px;
  border-left: 3px solid #3498db;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.data-row.long-content .data-label {
  margin-right: 0;
  margin-bottom: 8px;
  align-self: flex-start;
}

.data-value {
  flex: 1;
  color: #34495e;
  line-height: 1.6;
  word-break: break-all;
  padding: 8px 12px;
  background: #ffffff;
  border-radius: 6px;
  border: 1px solid #e1e8ed;
  min-height: 36px;
  display: flex;
  align-items: center;
  font-size: 14px;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05);
}


/* 数据表格样式 */
.data-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.data-table :deep(.el-table__header) {
  background-color: #f8f9fa;
}

.data-table :deep(.el-table__header th) {
  background-color: #f8f9fa;
  color: #606266;
  font-weight: 600;
  border-bottom: 2px solid #e4e7ed;
}

.data-table :deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

.data-table :deep(.el-table__row) {
  transition: background-color 0.2s ease;
}

/* 值类型样式 */
.value-string {
  color: #2c3e50;
  background: #ffffff;
}

.value-text {
  color: #2c3e50;
  background: #ffffff;
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.6;
  min-height: 60px;
  padding: 12px;
}

.value-number {
  color: #e67e22;
  font-weight: 600;
  font-family: 'Courier New', monospace;
  background: linear-gradient(135deg, #fff5e6 0%, #ffe0b3 100%);
  border-left-color: #e67e22 !important;
}

.value-date {
  color: #27ae60;
  font-weight: 500;
  background: linear-gradient(135deg, #e8f5e8 0%, #c8e6c9 100%);
  border-left-color: #27ae60 !important;
}

.value-boolean {
  color: #3498db;
  font-weight: 600;
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
  border-left-color: #3498db !important;
}

.value-dict {
  color: #6c757d;
  font-weight: 500;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-left-color: #6c757d !important;
}

/* 审批弹窗样式 */
.approval-dialog {
  :deep(.el-dialog) {
    border-radius: 12px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  }

  :deep(.el-dialog__header) {
    padding: 20px 24px 16px;
    border-bottom: 1px solid #f0f2f5;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-radius: 12px 12px 0 0;

    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: #2c3e50;
    }
  }

  :deep(.el-dialog__body) {
    padding: 0;
  }

  :deep(.el-dialog__footer) {
    padding: 0;
    border-top: 1px solid #f0f2f5;
  }
}

.approval-dialog-content {
  padding: 24px;
  background: #fff;
}

.approval-form-item {
  margin-bottom: 0;

  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #606266;
    font-size: 14px;
  }

  :deep(.el-textarea__inner) {
    border-radius: 8px;
    border: 1px solid #dcdfe6;
    font-size: 14px;
    line-height: 1.6;
    transition: all 0.3s ease;

    &:focus {
      border-color: #409eff;
      box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
    }

    &::placeholder {
      color: #c0c4cc;
      font-size: 13px;
    }
  }
}

.dialog-footer {
  padding: 20px 24px;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  background: #fafbfc;
  border-radius: 0 0 12px 12px;

  .el-button {
    min-width: 80px;
    border-radius: 6px;
    font-weight: 500;
  }
}

/* 悬浮审批按钮 */
.floating-approval-buttons {
  position: fixed;
  right: 30px;
  bottom: 30px;
  display: flex;
  flex-direction: row;
  gap: 12px;
  z-index: 1000;
}

.floating-button {
  height: 48px;
  padding: 0 20px;
  border-radius: 24px;
  font-size: 14px;
  font-weight: 500;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: none;
  min-width: 100px;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.2);
  }

  &:active {
    transform: translateY(0);
  }
}

.approve-button {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  border-color: #67c23a;

  &:hover {
    background: linear-gradient(135deg, #5daf34 0%, #7bc85a 100%);
    border-color: #5daf34;
  }
}

.reject-button {
  background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
  border-color: #f56c6c;

  &:hover {
    background: linear-gradient(135deg, #f45656 0%, #f67c7c 100%);
    border-color: #f45656;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {

  .json-container,
  .table-container {
    width: 95%;
  }

  .data-section {
    padding: 16px;
  }

  .json-display-content {
    padding: 16px 0;
  }

  .data-label {
    min-width: 120px;
    max-width: 160px;
  }
}

@media (max-width: 480px) {
  .floating-approval-buttons {
    right: 20px;
    bottom: 20px;
    flex-direction: row;
    gap: 8px;
  }

  .floating-button {
    height: 40px;
    padding: 0 16px;
    border-radius: 20px;
    font-size: 12px;
    min-width: 80px;
  }

  .json-card-with-button {
    padding-bottom: 20px;
  }

  .data-row {
    flex-direction: column;
    align-items: flex-start;
  }

  .data-label {
    min-width: auto;
    max-width: none;
    margin-right: 0;
    margin-bottom: 8px;
    width: 100%;
  }

  .data-value {
    width: 100%;
  }
}

/* 动画效果 */
.data-section {
  animation: fadeInUp 0.4s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 加载状态 */
.data-section.loading {
  opacity: 0.6;
  pointer-events: none;
}

/* 空状态 */
.data-section.empty {
  text-align: center;
  color: #909399;
  font-style: italic;
}

/* 数据行动画 */
.data-row {
  animation: slideInLeft 0.3s ease-out;
}

@keyframes slideInLeft {
  from {
    opacity: 0;
    transform: translateX(-20px);
  }

  to {
    opacity: 1;
    transform: translateX(0);
  }
}
</style>
